package com.example.lib_mvp.base.mvp;


import android.content.Context;

import androidx.annotation.NonNull;

import com.example.lib_mvp.base.AppBaseFragment;


public abstract class BaseMvpFragment<T extends BasePresenter> extends AppBaseFragment implements BaseView {

    @Override
    public void showLoading() {
        checkActivityAttached();
        getAttachActivity().loadIngDialogUtil.showLoadDialog("加载中...");
    }

    @Override
    public void showLoading(String msg) {
        checkActivityAttached();
        getAttachActivity().loadIngDialogUtil.showLoadDialog(msg);
    }

    @Override
    public void hideLoading() {
        checkActivityAttached();
        getAttachActivity().removeLoadIngDialog();
    }

    @Override
    public void showToast(String msg) {
        checkActivityAttached();
        getAttachActivity().showTipToast(msg, 2000);
    }

    @Override
    public void showErr() {
        checkActivityAttached();
        getAttachActivity().showErrorToast("异常");
    }

    protected boolean isAttachedContext() {
        return getActivity() != null;
    }

    /**
     * 检查activity连接情况
     */
    public void checkActivityAttached() {
        if (getActivity() == null) {
            throw new ActivityNotAttachedException();
        }
    }

    public static class ActivityNotAttachedException extends RuntimeException {
        public ActivityNotAttachedException() {
            super("Fragment has disconnected from Activity ! - -.");
        }
    }

    /**
     * 获取Presenter实例，子类实现
     */
    public abstract T getPresenter();

    public abstract void intPresenter();


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        intPresenter();
        if (getPresenter() != null) {
            getPresenter().attachView(this);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (getPresenter() != null) {
            getPresenter().detachView();
        }
    }
}